﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ERP.WebUI
{
    public class RoleRepository 
    {
        private EFDbContext db = new EFDbContext();
        public IQueryable<Role> Roles
        {
            get { return db.Roles; }
        }

        public OperationResult Insert(RoleModel model)
        {
            var entity = new Role
            {
                Name = model.Name,
                Description = model.Description,
                OrderSort = model.OrderSort,
                Enabled = model.Enabled
            };
            db.Entry<Role>(entity).State = EntityState.Added;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "添加成功");
        }

        public OperationResult Update(RoleModel model)
        {
            var entity = Roles.First(t => t.Id == model.Id);
            entity.Name = model.Name;
            entity.Description = model.Description;
            entity.OrderSort = model.OrderSort;
            entity.Enabled = model.Enabled;

            db.Set<Role>().Attach(entity);
            db.Entry<Role>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "更新成功");
        }

        public OperationResult Delete(int Id)
        {
            var model = Roles.FirstOrDefault(t => t.Id == Id);
            model.IsDeleted = true;

            db.Set<Role>().Attach(model);
            db.Entry<Role>(model).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "删除成功");
        }

        /// <summary>
        /// 复选框数据源
        /// </summary>
        /// <returns></returns>
        public List<KeyValueModel> GetKeyValueList()
        {
            var keyValueList = new List<KeyValueModel>();
            var dataList = Roles.Where(t => t.Enabled == true && t.IsDeleted == false)
                                .OrderBy(t => t.OrderSort)
                                .ToList();
            foreach (var data in dataList)
            {
                keyValueList.Add(new KeyValueModel { Text = data.Name, Value = data.Id.ToString() });
            }
            return keyValueList;
        }
    }
}